package com.bit.book.interceptor;

import com.bit.book.constant.Constants;
import com.bit.book.model.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean  preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //System.out.println("目标方法执行前……");
        log.info("登录拦截器进行拦截校验...");
        //判断用户是否登录
        HttpSession session = request.getSession(false);//false表示request中没有session不会创建一个session
        if(session == null ||
                !StringUtils.hasLength((String)session.getAttribute(Constants.SESSION_LOGIN_USER_NAME))){
            response.setStatus(401);//http状态码，不是业务码
            response.setContentType("text/html;charset=utf-8");//设置编码
            response.getOutputStream().write("用户未登录".getBytes(StandardCharsets.UTF_8));

            return false;
        }
        //true 放行，false 拦截
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        System.out.println("目标方法执行后……");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        System.out.println("视图渲染完成之后……");
    }
}
